/**
 * 593. 有效的正方形
 * https://leetcode-cn.com/problems/valid-square/
 */

/**
 * @param {number[]} p1
 * @param {number[]} p2
 * @return {number}
 */
function lengthBetweenTwoPoints(p1, p2) {
  const offsetX = p1[0] - p2[0];
  const offsetY = p1[1] - p2[1];
  return offsetX * offsetX + offsetY * offsetY;
}

/**
 * @param {number[]} p1
 * @param {number[]} p2
 * @param {number[]} p3
 * @param {number[]} p4
 * @return {boolean}
 */
function validSquare(p1, p2, p3, p4) {
  const len2 = lengthBetweenTwoPoints(p1, p2);
  const len3 = lengthBetweenTwoPoints(p1, p3);
  const len4 = lengthBetweenTwoPoints(p1, p4);
  let side1;
  let side2;
  let side3;
  let side4;
  let arrow1;
  let arrow2;
  if (len2 > len3 && len2 > len4) {
    side1 = len3;
    side2 = len4;
    side3 = lengthBetweenTwoPoints(p2, p3);
    side4 = lengthBetweenTwoPoints(p2, p4);
    arrow1 = len2;
    arrow2 = lengthBetweenTwoPoints(p3, p4);
  } else if (len3 > len2 && len3 > len4) {
    side1 = len2;
    side2 = len4;
    side3 = lengthBetweenTwoPoints(p3, p2);
    side4 = lengthBetweenTwoPoints(p3, p4);
    arrow1 = len3;
    arrow2 = lengthBetweenTwoPoints(p2, p4);
  } else if (len4 > len2 && len4 > len3) {
    side1 = len2;
    side2 = len3;
    side3 = lengthBetweenTwoPoints(p4, p2);
    side4 = lengthBetweenTwoPoints(p4, p3);
    arrow1 = len4;
    arrow2 = lengthBetweenTwoPoints(p2, p3);
  } else {
    return false;
  }
  return side1 === side2 && side2 === side3 && side3 === side4
    && arrow1 === arrow2;
}

console.log(validSquare([0, 0], [1, 1], [1, 0], [0, 1]) === true);
console.log(validSquare([0, 0], [1, 1], [1, 0], [0, 12]) === false);
console.log(validSquare([1, 0], [-1, 0], [0, 1], [0, -1]) === true);
